package com.pointstar.dp.modules.project.util;

/**
 * @author 朱科睿
 */
public class StringUtil {

    /**
     * ADT String
     * the implements of Operation Index()
     *
     * @param p   主串
     * @param t   子串
     * @param pos 起始位置
     * @return 子串在主串pos后第一次出现的位置
     */
    public static int index(String p, String t, int pos) {

        int pLength;
        int tLength;
        int currentPos;
        if (pos >= 0) {
            pLength = p.length();
            tLength = t.length();
            currentPos = pos;
            while (currentPos <= pLength - tLength) {
                if (p.substring(currentPos, currentPos + tLength).compareTo(t) != 0) {
                    currentPos++;
                    continue;
                }
                return currentPos;
            }
        }
        return 0;
    }

    public static int indexPatternMatch(String p, String t, int pos) {
        int currentPos;
        int currentT;
        if (pos >= 0) {
            currentPos = pos;
            currentT = 0;
            while (currentPos < p.length() && currentT < t.length()) {
                if (p.charAt(currentPos) == t.charAt(currentT)) {
                    ++currentPos;
                    ++currentT;
                    continue;
                }
                currentPos = currentPos - currentT + 1;
                currentT = 0;
            }
            if (currentT == t.length()) {
                return currentPos - t.length();
            }
        }
        return 0;
    }

    public static void main(String[] args) {
        String p = "worldCup";
        String t = "ld";
        int pos = 1;
        System.out.println(index(p, t, pos));
        System.out.println(indexPatternMatch(p, t, pos));
    }

}
